import axios from 'axios'
import config from '../config'
import { ElMessage } from 'element-plus'
import router from '../router'


const instance = axios.create({
    baseURL: config.baseURL || config.mockURL,
    // baseURL: 'http://localhost:3003',
    timeout: 6 * 1000,
});

const TOKEN_INVALID = 'Token认证失败,请重新登录'
const NETWORK_ERROR = '网络异常,请稍后重试'
const PARAM_ERROR = '格式错误'

// 添加请求拦截器
instance.interceptors.request.use((config) => {
    //获取token
    let data = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}')
    //结构出token没用就默认为空
    let { token = '' } = data
    //拉取请求头
    let header = config.headers
    //如果没有Authorization(授权)就添加一个Authorization(授权)并携带token
    if (!header.Authorization) header.Authorization = 'Bearer ' + token
    // 在发送请求之前做些什么
    return config;
}, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use((res: any) => {
    // 对响应数据做点什么
    const { data, msg, code } = res.data as any;
    if (code === 200) {
        return data;
    }
    if (code === 201) {
        ElMessage({
            message: '账号密码或验证码错误',
            type: 'error',
        })
        return Promise.reject(NETWORK_ERROR)
    }
    if (code === 50001) {
        ElMessage({
            message: NETWORK_ERROR,
            type: 'error',
        })
        return Promise.reject(NETWORK_ERROR)
    }
    if (code === 40001) {
        ElMessage({
            message: TOKEN_INVALID,
            type: 'error',
        })
        router.push('/login')
        return Promise.reject(TOKEN_INVALID)
    }
    if (code === 10001) {
        ElMessage({
            message: PARAM_ERROR,
            type: 'error',
        })
        return Promise.reject(PARAM_ERROR)
    }
    ElMessage.error(`Oops,${msg}`)
    return Promise.reject(msg)

}, (error) => {
    // 对响应错误做点什么
    return Promise.reject(error);
});

// console.log(instance.defaults.baseURL);

function request(options: any) {
    //判断是不是gte请求
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data || {}
    }
    //判断是不是mock模拟数据
    const isMock: boolean = options.mock && config.mock
    if (config.ENV == 'pro') {
        instance.defaults.baseURL = config.baseURL
    } else {
        instance.defaults.baseURL = isMock ? config.mockURL : config.baseURL
        // instance.defaults.baseURL = 'http://localhost:3003'
    }
    // console.log(instance.defaults.baseURL);

    return instance(options)
}

export default request;